/**
 * 
 */
package com.somobile.connection;

import java.util.Map;

/**
 * @author JatanP
 *
 */
public class SoUrlProvider implements ISoUrlProvider
{
	private String baseUrl;
	private String version;
	private String key;
	private static final String URL_SEPERATOR ="/";
	private static final String QP_SEPARATOR ="?";
	private static final String PARAM_SEPARATOR = "&";
	
	public String getBaseUrl()
	{
		return baseUrl;
	}
	public void setBaseUrl(String baseUrl)
	{
		this.baseUrl = baseUrl;
	}
	public String getVersion()
	{
		return version;
	}
	public void setVersion(String version)
	{
		this.version = version;
	}
	public String getKey()
	{
		return key;
	}
	public void setKey(String key)
	{
		this.key = key;
	}
	

	@Override
	public String formRequestURL(String subUrl)
	{
		
		return formUrl(subUrl);
	}
	
	@Override
	public String formRequestURL(String subUrl, Map<String, String> params)
	{
		String formedUrl = formUrl(subUrl);
		
		if(params == null || params.size() ==0)
		{
			return formedUrl;
		}
		
		StringBuilder sb = new StringBuilder(formedUrl.length()+params.size()*16);
		sb.append(formedUrl);
		for(String pName : params.keySet())
		{
			sb.append(SoUrlProvider.PARAM_SEPARATOR).append(pName).append('=').append(params.get(pName));
		}
		
		
		return sb.toString();
	}
	
	private String formUrl(String subUrl)
	{
		StringBuilder sb = new StringBuilder(baseUrl.length()+key.length()+subUrl.length()+version.length());
		
		sb.append(baseUrl).append(SoUrlProvider.URL_SEPERATOR).append(version);
		
		if(subUrl != null && !"".equals(subUrl))
		{
			sb.append(SoUrlProvider.URL_SEPERATOR).append(subUrl);
		}
		
		sb.append(SoUrlProvider.QP_SEPARATOR);
		sb.append("key=").append(key);
		
		return sb.toString();
	}
	
	@Override
	public String formRequestURL(String subUrl, String[][] params)
	{
		String formedUrl = formUrl(subUrl);
		
		if(params == null || params.length ==0)
		{
			return formedUrl;
		}
		
		StringBuilder sb = new StringBuilder(formedUrl.length()+params.length*16);
		sb.append(formedUrl);
		for(String[] param : params)
		{
			sb.append(SoUrlProvider.PARAM_SEPARATOR).append(param[0]).append('=').append(param[1]);
		}
		
		
		return sb.toString();
	}
	
}
